﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.BanHang
{
    public partial class FrmThongKeBanHang : BasicForms.FrmSupportPrintableComponents
    {
        private bool _NeedChooseAllVatTuHangHoa = true;
        private bool _NeedChooseAllDoiTac = true;

        public FrmThongKeBanHang()
        {
            InitializeComponent();
        }

        private void FrmThongKeBanHang_Load(object sender, EventArgs e)
        {
            try
            {
                cmbKyBaoCao.SelectedIndex = 19;

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                dsThongKeBanHang.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.GetDanhMucNhaCungCap().DataTable);
                dsThongKeBanHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);    //Lấy tất cả các hàng vì không dùng nhưng có thể đã bán
                gridControlDsDoiTac.DataSource = dsThongKeBanHang.DoiTuongNghiepVu;
                gridControlDsVatTuHangHoa.DataSource = dsThongKeBanHang.VatTuHangHoa;

                rItemGridLookUpEditNhomHangHoa.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            try
            {
                chkChooseAllDoiTac.Checked = true;
                chkChooseAllVatTuHangHoa.Checked = false;
                chkTKHangMuaTraLai.Checked = false;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (_NeedChooseAllVatTuHangHoa)
                {
                    dsThongKeBanHang.VatTuHangHoa.Clear();

                    string filterExpresstion = gridViewDsVatTuHangHoa.ActiveFilterString;
                    string[] separator = { "And" };
                    string[] stringSplited = filterExpresstion.Split(separator, StringSplitOptions.None);
                    foreach (string temp in stringSplited)
                    {
                        if (temp.Contains("NhomVatTuHangHoaID"))
                        {
                            filterExpresstion = temp.Replace("NhomVatTuHangHoaID", "Ten");
                            DataRow[] rows = DanhMucNhomVatTuHangHoa.Instance.DataTable.Select(filterExpresstion);
                            filterExpresstion = "NhomVatTuHangHoaID IN (";
                            foreach (DataRow row in rows)
                            {
                                filterExpresstion += "CONVERT('{" + row["ID"].ToString() + "}','System.Guid'), ";
                            }
                            if (filterExpresstion.EndsWith(", ")) filterExpresstion = filterExpresstion.Substring(0, filterExpresstion.Length - 2) + ")";
                            else if (filterExpresstion.EndsWith("(")) filterExpresstion = "";
                        }
                    }

                    foreach (string temp in stringSplited)
                    {
                        if (!temp.Contains("NhomVatTuHangHoaID") && temp != "")
                        {
                            filterExpresstion += string.Format(" AND {0}", temp);
                        }
                    }

                    DataView dv = DanhMucVatTuHangHoa.Filter(filterExpresstion).DataView;
                    dsThongKeBanHang.VatTuHangHoa.Merge(dv.ToTable());

                    foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
                    {
                        row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
                    }
                }
                else
                {
                    _NeedChooseAllVatTuHangHoa = true;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }
        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (_NeedChooseAllDoiTac)
                {
                    dsThongKeBanHang.DoiTuongNghiepVu.Clear();

                    DataView dv = DanhMucDoiTuongNghiepVu.Instance.Filter(gridViewDsDoiTac.ActiveFilterString).DataView;
                    dsThongKeBanHang.DoiTuongNghiepVu.Merge(dv.ToTable());

                    foreach (DataRow row in dsThongKeBanHang.DoiTuongNghiepVu.Rows)
                    {
                        row["Choose"] = chkChooseAllDoiTac.Checked;
                    }
                }
                else
                {
                    _NeedChooseAllDoiTac = true;
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                //Merge lại để check những hàng đã check từ trước và uncheck những hàng khác
                dsThongKeBanHang.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Instance.DataTable);
                foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
                {
                    if (!(row["Choose"] is bool)) row["Choose"] = false;
                }

                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;

            string kyBaoCao = cmbKyBaoCao.Text;

            if (kyBaoCao == "Cả năm") kyBaoCao = "Năm \n" + GeneralLibs.Config.NamTaiChinh.ToString();
            else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                       ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                       ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);

            BasicForms.FrmProgressBar.StartShowProgress();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                
                string nhaCungCapCondition = "1 = 1";
                if (!chkChooseAllDoiTac.Checked)
                {
                    nhaCungCapCondition = "B.DoiTuongNghiepVu1ID IN (";

                    foreach (DataRow row in dsThongKeBanHang.DoiTuongNghiepVu.Rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            nhaCungCapCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (nhaCungCapCondition.EndsWith("', ")) nhaCungCapCondition = nhaCungCapCondition.Substring(0, nhaCungCapCondition.Length - 2) + ")";
                    else nhaCungCapCondition = "1 = 0";
                }

                string vatTuHangHoaCondition = "1 = 1";
                if (!chkChooseAllVatTuHangHoa.Checked)
                {
                    DataRow[] rows = dsThongKeBanHang.VatTuHangHoa.Select("Choose = 1");
                    vatTuHangHoaCondition = "C.VatTuHangHoa1ID IN  (";
                    foreach (DataRow row in rows)
                    {
                        if ((bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith("', ")) vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }

                string nhomVatTuHangHoaCondition = "1 = 1";
                if (gridViewDsVatTuHangHoa.ActiveFilterString.Contains("NhomVatTuHangHoaID"))
                {
                    nhomVatTuHangHoaCondition = gridViewDsVatTuHangHoa.ActiveFilterString;
                    string[] separator = { "And" };
                    string[] stringSplited = nhomVatTuHangHoaCondition.Split(separator, StringSplitOptions.None);
                    foreach (string temp in stringSplited)
                    {
                        if (temp.Contains("NhomVatTuHangHoaID"))
                        {
                            nhomVatTuHangHoaCondition = temp.Replace("NhomVatTuHangHoaID", "Ten");
                            DataRow[] rows = DanhMucNhomVatTuHangHoa.Instance.DataTable.Select(nhomVatTuHangHoaCondition);
                            nhomVatTuHangHoaCondition = "E.ID IN (";
                            foreach (DataRow row in rows)
                            {
                                nhomVatTuHangHoaCondition += string.Format("'{0}', ", row["ID"]);
                            }
                            if (nhomVatTuHangHoaCondition.EndsWith(", ")) nhomVatTuHangHoaCondition = nhomVatTuHangHoaCondition.Substring(0, nhomVatTuHangHoaCondition.Length - 2) + ")";
                            else if (nhomVatTuHangHoaCondition.EndsWith("(")) nhomVatTuHangHoaCondition = "";
                        }
                    }
                }

                string khoCondition = "1 = 1";
                if ((Guid)cmbKho.EditValue != Guid.Empty) khoCondition = string.Format("B.Kho1ID = '{0}'", cmbKho.EditValue);

                string loaiChungTuBanCondition = "N'HoaDonBanHang'";
                if (chkThongKeCaHoaDonBanLe.Checked) loaiChungTuBanCondition = "N'HoaDonBanHang', N'HoaDonBanLe'";

                cmd.CommandText = string.Format("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
                cmd.ExecuteNonQuery();

                if (!chkTKHangMuaTraLai.Checked)
                {
                    cmd.CommandText = string.Format("SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia, C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau, C.Value6 GiaThanhToan, \n" +
                                               "    C.Value7 ThanhTienThanhToan, A.SoTienNT TongTienTheoHoaDon, PTBH.Ten PhuongThucThanhToan \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN({0}) AND A.GhiSo = 1  \n" +
                                               "	AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{1} \n" +
                                               "	AND {2} \n" +
                                               "	AND {3} \n" +
                                               "	AND {4} \n" +
                                               "    AND C.Value5 IS NOT NULL AND C.Value3 IS NOT NULL \n",
                                               //"ORDER BY A.Ngay \n",
                                               loaiChungTuBanCondition , nhaCungCapCondition, vatTuHangHoaCondition, khoCondition, nhomVatTuHangHoaCondition);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia, C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau, C.Value6 GiaThanhToan, \n" +
                                               "    C.Value7 ThanhTienThanhToan, A.SoTienNT TongTienTheoHoaDon, PTBH.Ten PhuongThucThanhToan \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN({0}) AND A.GhiSo = 1  \n" +
                                               "	AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{1} \n" +
                                               "	AND {2} \n" +
                                               "	AND {3} \n" +
                                               "	AND {4} \n" +
                                               "UNION \n" +
                                               "SELECT A.So, A.Ngay, DTNV.Ten TenDoiTac, Kho.Ten TenKho, D.Ten TenHangHoa, E.Ten TenNhomHangHoa, D.DonViTinh, \n" +
                                               "	C.Value1 SoLuong, C.Value12 GiaBia, C.Value13 ThanhTienGiaBia, C.Value8 ChietKhau, -C.Value6 GiaThanhToan, \n" +
                                               "    -C.Value7 ThanhTienThanhToan, -A.SoTienNT TongTienTheoHoaDon, PTBH.Ten PhuongThucThanhToan \n" +
                                               "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n" +
                                               "	INNER JOIN ChungTu B ON A.ChungTuID = B.ChungTuGocID  \n" +
                                               "	INNER JOIN  KhoanMucChungTu C ON B.ChungTuID = C.ChungTuID  \n" +
                                               "	INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n" +
                                               "	INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID  \n" +
                                               "	INNER JOIN DoiTuongNghiepVu DTNV ON B.DoiTuongNghiepVu1ID = DTNV.ID  \n" +
                                               "	INNER JOIN Kho ON B.Kho1ID = Kho.ID  \n" +
                                               "    LEFT JOIN PhuongThucThanhToanBanHang PTBH ON A.PhuongThucThanhToanMuaBanHangID = PTBH.ID \n" +
                                               "WHERE LCT.Ma IN('HangBanTraLai') AND A.GhiSo = 1  \n" +
                                               "	AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi \n" +
                                               "	AND	{1} \n" +
                                               "	AND {2} \n" +
                                               "	AND {3} \n" +
                                               "	AND {4} \n" ,
                                               //"ORDER BY A.Ngay \n",
                                                loaiChungTuBanCondition, nhaCungCapCondition, vatTuHangHoaCondition, khoCondition, nhomVatTuHangHoaCondition);
                }

                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                dsThongKeBanHang.Detail_ThongKeBanHang.Clear();
                DataTable dt = new DataTable();
                da.Fill(dsThongKeBanHang.Detail_ThongKeBanHang);
                gridControl.DataSource = dsThongKeBanHang.Detail_ThongKeBanHang;
                FormatNumberInGridView(gridView);
                FormatNumberInGridView(gridViewDsDoiTac);
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
                colNgay.SortMode = DevExpress.XtraGrid.ColumnSortMode.Value;
                colNgay.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeader(true, gridControl, true, true, "Thống kê bán hàng", "");
        }

        private void gridViewDsVatTuHangHoa_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            int existedRowHandle = -1;
            foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
            {
                existedRowHandle++;
                if (e.RowHandle == existedRowHandle)
                { 
                    string value = row["Choose"].ToString();
                    if (value == "False" || value == "")
                    {
                        row["Choose"] = true;
                    }
                    else if( value == "True")
                    {
                        row["Choose"] = false;
                    }
                }
            }
        }

        private void gridViewDsVatTuHangHoa_ColumnFilterChanged(object sender, EventArgs e)
        {
            try
            {
               int countOldRow = dsThongKeBanHang.VatTuHangHoa.Rows.Count;
                //Lọc điều kiện nhóm hàng hóa
                string filterExpresstion = gridViewDsVatTuHangHoa.ActiveFilterString;
                string[] separator = { "And" };
                string[] stringSplited = filterExpresstion.Split(separator, StringSplitOptions.None);
                foreach (string temp in stringSplited)
                {
                    if (temp.Contains("NhomVatTuHangHoaID"))
                    {
                        filterExpresstion = temp.Replace("NhomVatTuHangHoaID", "Ten");
                        DataRow[] rows = DanhMucNhomVatTuHangHoa.Instance.DataTable.Select(filterExpresstion);
                        filterExpresstion = "NhomVatTuHangHoaID IN (";
                        foreach (DataRow row in rows)
                        {
                            filterExpresstion += "CONVERT('{" + row["ID"].ToString() + "}','System.Guid'), ";
                        }
                        if (filterExpresstion.EndsWith(", ")) filterExpresstion = filterExpresstion.Substring(0, filterExpresstion.Length - 2) + ")";
                        else if (filterExpresstion.EndsWith("(")) filterExpresstion = "";
                    }
                }

                foreach (string temp in stringSplited)
                {
                    if (!temp.Contains("NhomVatTuHangHoaID") && temp !="")
                    {
                        filterExpresstion += string.Format(" AND {0}", temp );
                    }
                }

                DataView dv = DanhMucVatTuHangHoa.Filter(filterExpresstion).DataView;
                dsThongKeBanHang.VatTuHangHoa.Merge(dv.ToTable());
                foreach (DataRow row in dsThongKeBanHang.VatTuHangHoa.Rows)
                {
                    if (!(row["Choose"] is bool)) row["Choose"] = false;
                }
                int countNewRow = dsThongKeBanHang.VatTuHangHoa.Rows.Count;

                //Thay đổi tăng số dòng lên thì phải bỏ CheckAll
                if(countNewRow > countOldRow)
                {
                    _NeedChooseAllVatTuHangHoa = false;
                    chkChooseAllVatTuHangHoa.Checked = false;
                }

            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            
        }
        private void gridViewDsDoiTac_ColumnFilterChanged(object sender, EventArgs e)
        {
            try
            {
                int countOldRow = dsThongKeBanHang.DoiTuongNghiepVu.Rows.Count;

                DataView dv = DanhMucDoiTuongNghiepVu.Instance.Filter(gridViewDsDoiTac.ActiveFilterString).DataView;
                dsThongKeBanHang.DoiTuongNghiepVu.Merge(dv.ToTable());

                dsThongKeBanHang.DoiTuongNghiepVu.Merge(dv.ToTable());
                foreach (DataRow row in dsThongKeBanHang.DoiTuongNghiepVu.Rows)
                {
                    if (!(row["Choose"] is bool)) row["Choose"] = false;
                }
                int countNewRow = dsThongKeBanHang.DoiTuongNghiepVu.Rows.Count;

                //Thay đổi tăng số dòng lên thì phải bỏ CheckAll
                if (countNewRow > countOldRow)
                {
                    _NeedChooseAllDoiTac = false;
                    chkChooseAllDoiTac.Checked = false;
                }

            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }

        }
    }
}
